package org.phantom.securityframework.datapermission.internal;

import java.lang.annotation.Annotation;

import org.phantom.securityframework.datapermission.DataFilter;
import org.phantom.securityframework.datapermission.DimensionQuery;
import org.phantom.securityframework.datapermission.QueryParameters;
import org.springframework.stereotype.Service;

@Service("sqlBuildOracleImpl")
public class SqlBuildOracleImpl extends SqlBuildDefaultImpl {

	@Override
	public String build(Annotation anno, DimensionQuery dimensionQuery) {
		DataFilter dataFilter = (DataFilter) anno;
		DimensionQueryDefaultImpl query = (DimensionQueryDefaultImpl) dimensionQuery;
		QueryParameters pager = query.getParameters();
		StringBuilder sb = new StringBuilder("select * from (select ");
		if(pager.getPage()!=0){
			sb.append("t.*,rownum rn ");
		}else{
			sb.append("* ");
		}
		sb.append("from (select * from ").append(dataFilter.table());
		if(query==null || query.getDimensionMappedValue()==null){
			sb.append(")");
			return sb.toString();
		}
		sb.append(this.buildCondition(anno, query)).append(")t");
		if(pager.getPage()!=0){
//			计算分页移植到DimensionQueryCreatorOracleImpl中
//			sb.append(" where rownum<").append((pager.getRows()*pager.getPage()+1)+"").append(") where rn>").append((pager.getPage()-1)*pager.getRows());
			sb.append(" where rownum<").append(pager.getPage()).append(") where rn>").append(pager.getRows());
			
		}else{
			sb.append(")");
		}
		if(pager.getOrder()!=null){
			sb.append(" order by ").append(pager.getOrder()).append(" ").append(pager.getSort()==null?"asc":pager.getSort());
		}
		return sb.toString();
	}
}
